<script setup>
import { ref, reactive, onMounted, nextTick, h } from 'vue';
import { ElMessage } from 'element-plus';
import { statementApi as MainApi, statementById as MainById, unitApi, sensorApi, statementitemApi, roleTree, statementAdd, statementByIdChange } from '@T2/service/api.ts';
import { useIuserInfoStore, useCurrentWatchStore } from '@T2/store/users.ts';
import { deepCopy } from '@T2/utils/utils.ts';
import dayjs from 'dayjs';
import SelectOption from '@T2/views/Project/Manage/components/select/option.vue';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { info } = iuserInfoStore;

const { type, row, dftData, options } = defineProps({
  type: {
    type: String,
    validator(value) {
      return ['新增', '编辑'].includes(value);
    },
    required: true,
  },
  row: {
    type: [Object, null],
    required: true,
  },
  dftData: {
    type: [Object, null],
    required: true,
  },
  options: {
    type: Array,
    required: true,
  },
});
const emits = defineEmits(['closed']);
const showRf = ref(true);

onMounted(async () => {
  if (type === '新增') {
    Rt.form = {
      last_save_data_time: dayjs().add(1, 'hour').format('YYYY-MM-DD HH') + ':00:00',
      refresh: 1,
      unit: '天',
      ...(dftData || {}),
    };
    Rt.table = [];
    Rt.table_waitIds = [];
    initTreeRt();
  } else if (type === '编辑') {
    const { id, name, last_save_data_time, refresh, unit, users, option } = deepCopy(row);
    Rt.form = { id, name, last_save_data_time, refresh, unit, users, option_id: option };
    Rt.table = [];
    Rt.table_waitIds = [];
    Rt.editIdsObj = {};
    const statementitems = await getStatementitem(row.id);
    statementitems.forEach(item => {
      Rt.sensorNode[item.sensor] = item.name;
      
      /* 创建statementitem对象 */
      const { id, sensor, name, sensor_name, sensor__recordcirle, sensor__recordcirle_unit, sensor_unit, type } = item;
      let table = {
        id,
        sensor,
        name,
        _name: sensor_name,
        recordcirle: sensor__recordcirle,
        recordcirle_unit: sensor__recordcirle_unit,
        unit: sensor_unit,
        type,
      };
      Rt.table.push(table);
      Rt.table_waitIds.push(table.sensor);
      Rt.editIdsObj[sensor] = id;
    });
    initTreeRt();
  }
  getRoleTree();
});

const Rt = reactive({
  form: {},
  
  table: [],
  table_waitIds: [],/* 因为左侧列表变量不是一次性就加载，临时存放未加载的变量 */
  
  cascaderProps: { multiple: true, emitPath: false },
  iusersByRole: [],
  
  editIdsObj: {},
  sensorNode: {},
});
const FormRef = ref(null);
const treeRt = reactive({
  units: [],
  data: [],
  sensors: [],
  search: '',
});
const initTreeRt = async () => {
  treeRt.data = [];
  treeRt.sensors = [];
  treeRt.search = '';
  if (!treeRt.units.length) {
    treeRt.units = await getUnits();
    treeRt.units.push({ isInner: true, name: '内部变量' });
  }
  treeRt.data = deepCopy(treeRt.units);
  if (treeRt.data.length === 1) {
    changeUnit(treeRt.data[0]);
  }
  nextTick(() => {
    FormRef.value.clearValidate();
  });
}
const getUnits = () => {
  return new Promise((resolve, reject) => {
    unitApi({
      method: 'get',
      params: {
        ordering: '-create_time',
        warn: true,
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject([]);
    });
  });
}
const changeUnit = async (item) => {
  const { isInner, id, opened } = item;
  treeRt.data.forEach(i => i.opened = false);
  item.opened = !opened;
  if (item.children) {
    return;
  }
  if (isInner) {
    item.children = await getInnerSensors();
  } else {
    item.children = await getSensors(id);
  }
  /* 反选复选框 */
  Rt.table.forEach(table => {
    let sensor = item.children.find(i => i.id === table.sensor);
    if (sensor) {
      treeRt.sensors.push(sensor);
      Rt.table_waitIds = Rt.table_waitIds.filter(i => sensor.id !== i);
    }
  });
}
const getSensors = (unitID) => {
  return new Promise((resolve, reject) => {
    sensorApi({
      method: 'get',
      params: {
        device__unit: unitID,
        recordcirle__isnull: false,
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject([]);
    });
  });
}
const getInnerSensors = () => {
  return new Promise((resolve, reject) => {
    sensorApi({
      method: 'get',
      params: {
        type: '内部变量',
        recordcirle__isnull: false,
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject([]);
    });
  });
}
const getStatementitem = (statementID) => {
  return new Promise((resolve, reject) => {
    statementitemApi({
      method: 'get',
      params: {
        statement: statementID,
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject([]);
    });
  });
}


/* 选择所属分组 */
const handleOptionSelectChange = (data, node) => {
  Rt.form.option_id = data?.id || null;
}
const optionSelectClear = () => {
  Rt.form.option_id = null;
}

/* 推送人员 */
const getRoleTree = () => {
  if (Rt.iusersByRole.length) {
    return;
  }
  roleTree({
    method: 'get',
    params: {},
  }).then(res => {
    if (!res?.length) {
      return;
    }
    const list = res.filter(i => i.children?.length);
    list.forEach(role => {
      role.value = role.id;
      role.label = role.name;
      role.children?.forEach(iuser => {
        iuser.value = iuser.id;
        iuser.label = iuser.truename;
        iuser.leaf = true;
      });
    });
    Rt.iusersByRole = list;
  })
}
const handleCheckedChange = (value) => {
  /* 当前传入的value:变量对象*/
  for (let i = Rt.table.length - 1; i >= 0; i--) {
    const table = Rt.table[i];
    if (!value.find(j => j.id === table.sensor) && !Rt.table_waitIds.includes(table.sensor)) {
      Rt.table.splice(i, 1);
    }
  }
  value.forEach(item => {
    if (!Rt.sensorNode[item.id]) {
      Rt.sensorNode[item.id] = item.name;
    }
    if (!Rt.table.find(table => table.sensor === item.id)) {
      /* 创建statementitem对象 */
      const { id: sensor, name: _name, recordcirle, recordcirle_unit, unit } = item;
      let table = {
        id: Rt.editIdsObj[sensor] || null,
        sensor,
        name: Rt.sensorNode[sensor],
        _name,
        recordcirle,
        recordcirle_unit,
        unit,  //单位
        type: '报表',
      };
      Rt.table.push(table);
    }
  });
}
/* statementitem的table操作 */
const scopeNameChange = (row, value) => {
  Rt.sensorNode[row.sensor] = row.name;
}

const handleSubmit = async () => {
  const isValid = await FormRef.value.validate(valid => valid);
  if (!isValid) {
    return;
  }
  if (Rt.table.length >= 8) {
    ElMessage.error('一组曲线不可超过8个变量！');
    return;
  }
  if (type === '新增') {
    AddMain();
  } else if (type === '编辑') {
    EditMain();
  }
}
const AddMain = () => {
  const items = Rt.table.map(item => {
    return {name: item.name, sensor: item.sensor, type: item.type}
  });
  statementAdd({
    method: 'post',
    data: {
      ...Rt.form,
      project: curProject.id,
      create_user: info.id,
      rtype: '报表',
      type: '',
      items,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    handleCancel(true);
  }).catch(res => {
    ElMessage.error('新增失败');
    handleCancel(true);
  });
}
const EditMain = () => {
  const items = Rt.table.map(item => {
    return { id: item.id, name: item.name, sensor: item.sensor, type: item.type}
  });
  statementByIdChange({
    method: 'put',
    id: Rt.form.id,
    data: {
      ...Rt.form,
      items,
      project: curProject.id,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    handleCancel(true);
  }).catch(res => {
    ElMessage.error('编辑失败');
    handleCancel(true);
  });
}

const handleCancel = (refresh = false) => {
  emits('closed', refresh);
}
</script>

<template>
  <div>
    <el-dialog v-model="showRf" :title="`${ type }报表`" width="1000px" @closed="handleCancel()">
      <el-form
        ref="FormRef"
        :model="Rt.form"
        label-width="100px"
        class="flex flex-wrap"
      >
        <el-form-item prop="name" style="width: 50%;" label="报表名称：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
          <el-input v-model="Rt.form.name"></el-input>
        </el-form-item>
        <el-form-item prop="option_id" style="width: 50%;" label="所属分组：">
          <SelectOption
            type="报表分组"
            :option="Rt.form.option_id"
            @current-change="handleOptionSelectChange"
            @clear="optionSelectClear"
          />
        </el-form-item>
        <el-form-item label="记录时间：" style="width: 50%;">
          <el-date-picker
            v-model="Rt.form.last_save_data_time"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择开始记录的时间"
            :clearable="false"
            :teleported="false"
          />
        </el-form-item>
        <el-form-item label="采样周期：" style="width: 50%;">
          <div class="flex" style="gap: 5px;">
            <el-input-number style="width: 70px;" :controls="false" v-model="Rt.form.refresh"></el-input-number>
            <el-select style="width: 120px;" v-model="Rt.form.unit">
              <el-option label="分钟" value="分钟"></el-option>
              <el-option label="小时" value="小时"></el-option>
              <el-option label="天" value="天"></el-option>
              <el-option label="周" value="周"></el-option>
              <el-option label="月" value="月"></el-option>
              <el-option label="年" value="年"></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
      
      <hr />
      
      <div class="flex">
        <div class="sensors-box flex-column" style="gap: 12px;">
          <label class="sen-title">源列表</label>
          <el-input v-model="treeRt.search" placeholder="输入名称进行筛选..." >
            <template #suffix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <div class="us-box flex-column scroller-aside">
            <template v-for="item in treeRt.data">
              <div class="flex--center pointer" @click="changeUnit(item)">
                <el-icon color="#a8abb2" size="12" style="margin-right: 4px;">
                  <CaretRight v-if="!item.opened" />
                  <CaretBottom v-else />
                </el-icon>
                <label class="unit-name pointer" :class="{ 'isActive': item.opened }">
                  <span>{{ item.name }}</span>
                  ({{ item.children ? item.children.length : '...' }})
                </label>
              </div>
              <el-checkbox-group
                v-if="item.children && item.opened"
                class="check-box flex-column"
                v-model="treeRt.sensors"
                name="checkname"
                @change="handleCheckedChange"
              >
                <el-checkbox
                  v-show="!item.hide"
                  v-for="item in item.children"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-checkbox-group>
            </template>
          </div>
        </div>
        <div class="right-box flex-column" style="gap: 12px;">
          <label class="sen-title">目标列表</label>
          <el-table
            :data="Rt.table" 
            scrollbar-always-on
            :header-cell-style="{backgroundColor: '#fafafa'}"
            style="max-height: 400px;margin-bottom: 0;"
          >
            <el-table-column type="index" label="序号" align="center" width="65" />
            <el-table-column prop="name" label="表头名称" min-width="180">
              <template #default="scope">
                <el-input v-model="scope.row.name" @input="scopeNameChange(scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="_name" label="数据名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="recordcirle" label="存储周期" min-width="100" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.recordcirle + scope.row.recordcirle_unit }}
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" min-width="100" />
          </el-table>
        </div>
      </div>
    
      <hr />
      <div class="flex--center" style="margin: 10px;">
        <label style="width: 60px;white-space: nowrap;">权限：</label>
        <el-cascader
          style="width: 90%;"
          v-model="Rt.form.users"
          :options="Rt.iusersByRole"
          :props="Rt.cascaderProps"
          :show-all-levels="false"
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="4"
          clearable
        />
      </div>
      
      <template #footer>
        <div style="flex: auto">
          <el-button @click="showRf = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit()">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
hr {
  border: none;
  border-bottom: 1px solid #e9e9e9;
  margin: 0;
}
.sensors-box {
  height: 450px;
  width: 280px;
  border-right: 1px solid #e9e9e9;
  padding: 8px 16px 0 0;
}
label.sen-title {
  font-weight: 500;
  font-size: 16px;
  color: #666666;
}
.us-box {
  flex: 1;
  overflow: auto;
  .unit-name {
    color: rgba(18, 30, 52, 0.8);
    font-size: 12px;
    &.isActive {
      color: #4d92f5;
    }
  }
}
.right-box {
  flex: 1;
  padding: 8px 16px 0;
}
</style>

<style scoped>
:deep(.statement-filter.el-input) {
  margin-bottom: 8px;
}
:deep(.statement-filter .el-input__wrapper) {
  box-shadow: none;
  border-bottom: 1px solid rgba(0,0,0,0.1);
  border-radius: 0;
}
:deep(.statement-filter .el-input__inner) {
  color: #121E34;
}

:deep(.el-tree) {
  flex: 1;
  overflow: overlay;
  overflow-x: hidden;
  border-radius: 3px;
  padding: 4px 0;
}
:deep(.is-current>.el-tree-node__content) {
  background-color: #F1F4FA !important;
}
:deep(.el-tree .el-icon) {
  margin-right: 4px;
}
:deep(.el-tree .el-tree-node__label) {
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  position: relative;
}

:deep(.el-picker-panel__footer button.is-text) {
  /* 隐藏日期的【此刻】按钮 */
  display: none;
}

/* 多选变量 */
:deep(.el-checkbox) {
  margin: 0 20px;
  height: 25px;
}
:deep(.check-box .el-checkbox__label) {
  width: 200px;
  font-size: 12px;
  line-height: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>